package clickCaptcha

import (
	"context"
	"gdshop-back-end-go/common/libs/myCache"
	"github.com/gogf/gf/util/gconv"
	"github.com/wenlng/go-captcha/captcha"
	"strings"
	"time"
)

var keyPrefix = "captcha:"

func Generate(ctx context.Context) (map[string]interface{}, error) {
	capt := captcha.GetCaptcha()
	dots, b64, tb64, key, err := capt.Generate()
	if err != nil {
		return nil, err
	}
	// 缓存验证码
	err = myCache.Set(keyPrefix+key, gconv.String(dots), time.Minute*5)
	if err != nil {
		return nil, err
	}

	return map[string]interface{}{
		"image_base64": b64,
		"thumb_base64": tb64,
		"captcha_key":  key,
	}, nil
}

func CaptchaCheck(ctx context.Context, captchaKey, captchaDots string) (bool, error) {
	// 获取缓存的验证码
	cacheData, err := myCache.Get(keyPrefix + captchaKey)
	if err != nil {
		return false, err
	}
	var dct map[int]captcha.CharDot
	err = gconv.Scan(cacheData, &dct)
	if err != nil {
		return false, err
	}
	src := strings.Split(captchaDots, ",")
	if (len(dct) * 2) != len(src) {
		return false, nil
	}

	chkRet := false
	var j, k int
	for i, dot := range dct {
		j = i * 2
		k = i*2 + 1
		// 校验点的位置,在原有的区域上添加额外边距进行扩张计算区域,不推荐设置过大的padding
		// 例如：文本的宽和高为30，校验范围x为10-40，y为15-45，此时扩充5像素后校验范围宽和高为40，则校验范围x为5-45，位置y为10-50
		chkRet = captcha.CheckPointDistWithPadding(gconv.Int64(src[j]), gconv.Int64(src[k]),
			int64(dot.Dx), int64(dot.Dy), int64(dot.Width), int64(dot.Height), 5)
		if !chkRet {
			break
		}
	}

	if !chkRet {
		return false, nil
	}

	// 验证成功后删除缓存
	myCache.Delete(keyPrefix + captchaKey)

	return true, nil
}
